import hashlib
import os
import time

from django.db import models
from django.utils import six
from django.utils.crypto import get_random_string

from mysite import utils


class AvatarField(models.ImageField):
    def get_filename(self, filename):
        return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))

    def generate_filename(self, instance, filename):
        filename = self.get_filename(filename)
        basename, ext = os.path.splitext(filename)
        basename = hashlib.md5(basename + six.text_type(time.time())
                               + six.text_type(get_random_string(6))).hexdigest()
        return os.path.join(basename[0:2], basename[2:4], basename + ext)

    def pre_save(self, model_instance, add):
        file = super(AvatarField, self).pre_save(model_instance, add)
        if file:
            im = utils.image_center_resize(file.path, (100, 100))
            im.save(file.path)
        return file

from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^account\.fields\.AvatarField"])
